package com.avic.process.utils;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;

import com.teamcenter.rac.aif.AbstractAIFDialog;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentBOMLine;
import com.teamcenter.rac.kernel.TCComponentBOMWindow;
import com.teamcenter.rac.kernel.TCComponentBOMWindowType;
import com.teamcenter.rac.kernel.TCComponentForm;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.pse.PSEApplicationPanel;
import com.teamcenter.rac.pse.common.BOMPanel;
import com.teamcenter.rac.pse.common.BOMTreeTable;
import com.teamcenter.rac.pse.plugin.Activator;
import com.teamcenter.rac.pse.services.PSEApplicationService;


@SuppressWarnings({ "serial" })
public class RelatedItemTreeDialog extends AbstractAIFDialog implements ActionListener, TreeSelectionListener
{
	private static final MyLogger logger = MyLogger.getLoggerObject(RelatedItemTreeDialog.class);
	public static final String NXAssembly = "P5NXassemblyRevision";
	public static final String CATIAAssembly = "P5CATassemblyRevision";
	public static final String NoImage = "P5noimagepartRevision";
	public static final String NXStanard = "P5NXstandardRevision";
	public static final String CATIAStandard = "P5CATIAstandardRevision";
	public static final String Purchase = "P5purchaseRevision";
	public static final String Auxiliary = "P5auxiliaryRevision";
	public static final String GYXAuxiliary = "P5materialRevision";
	public static final String GYpart = "P5gypartRevision";
	public static final String GYmaterial = "P5materialRevision";
	private JButton btnOK;
	private JButton btnCancel;
	private String[] nodeTypes;
	private JLabel	label;
	private WeldItem[] weldItems;
	private InsulationMaterial[] insulationMaterials;
	private WireMaterial[]	wireMaterials;
	private AssemblyItem[]	assemblyItems;
	private WaveSolderingItem[]	waveSolderingItems;
	private BOMTreeTable bomTreeTable;
	private TCComponentBOMLine[]	bomlines;
	private String[]	auxMaterials;
	private List<TCComponentItemRevision> listItemR;
	private List<TCComponentItemRevision> list;
	
	public RelatedItemTreeDialog(JFrame owner, TCComponentItemRevision itemRev, String[] nodeTypes) 
	{
		super(owner);
		dialogResultId = ID_CLOSE;
		this.nodeTypes = nodeTypes;
		setModal(true);
		setResizable(false);
		setLocationRelativeTo(owner);
		setTitle("\u5173\u8054\u7684\u96F6\u7EC4\u4EF6\u6811");
		setIconImage(Toolkit.getDefaultToolkit().getImage(RelatedItemTreeDialog.class.getResource("/com/kostech/process/utils/images/teamcenter16.png")));
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		setPreferredSize(new Dimension(830, 500));
		getContentPane().setLayout(null);
		
		label = new JLabel("\u710A\u63A5\u5DE5\u5E8F\u5173\u8054\u7684\u96F6\u7EC4\u4EF6\u7C7B\u578B\uFF1ANX\u81EA\u5236\u4EF6\u3001CATIA\u81EA\u5236\u4EF6");
		label.setBounds(10, 10, 804, 15);
		getContentPane().add(label);
		
		btnOK = new JButton("\u786E  \u5B9A");
		btnOK.setBounds(614, 440, 95, 25);
		btnOK.setEnabled(false);
		getContentPane().add(btnOK);
		btnOK.addActionListener(this);
		
		btnCancel = new JButton("\u53D6  \u6D88");
		btnCancel.setBounds(719, 440, 95, 25);
		getContentPane().add(btnCancel);
		btnCancel.addActionListener(this);
		
		JPanel panel = new JPanel();
		panel.setBounds(10, 35, 804, 395);
		getContentPane().add(panel);
		panel.setLayout(new BorderLayout(0, 0));

		try
		{
			PSEApplicationService pseAppService = (PSEApplicationService) Activator.getPSEService();
			PSEApplicationPanel psePane = new PSEApplicationPanel(pseAppService);
			psePane.open(itemRev, null, null, true);
			BOMPanel bom = psePane.getCurrentBOMPanel();
			bomTreeTable = bom.getTreeTable();
			bomTreeTable.addTreeSelectionListener(this);
			panel.add(bom, BorderLayout.CENTER);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			logger.error(e);
		}
	}
	
	public void setLabel(String text)
	{
		this.label.setText(text);
	}
	
	@Override
	public void actionPerformed(ActionEvent e)
	{
		Object src = e.getSource();
		if (src.equals(btnOK))
		{
			dialogResultId = ID_OK;
			weldItems = new WeldItem[bomlines.length];
			wireMaterials = new WireMaterial[bomlines.length];
			assemblyItems = new AssemblyItem[bomlines.length];
			waveSolderingItems = new WaveSolderingItem[bomlines.length];
			insulationMaterials = new InsulationMaterial[bomlines.length];
			auxMaterials = new String[bomlines.length];
			listItemR = new ArrayList<TCComponentItemRevision>();
			try
			{
				for (int i = 0; i < bomlines.length; i++)
				{
					TCComponentItemRevision itemRev = bomlines[i].getItemRevision();
					String bomcount = bomlines[i].getProperty("bl_quantity");
					bomcount = bomcount.isEmpty() ? "1" : bomcount;
					if (list == null) {
						weldItems[i] = getWeldItem(itemRev);
						wireMaterials[i] = getWireMaterial(itemRev,bomcount);
						assemblyItems[i] = getAssemblyItem(itemRev);
						waveSolderingItems[i] = getWaveSolderingItem(itemRev);
						insulationMaterials[i] = getInsulationMaterial(itemRev,bomcount);
						auxMaterials[i] = getAuxMaterial(itemRev);
					}else{
						if (!list.contains(itemRev)) {
							listItemR.add(itemRev);
							weldItems[i] = getWeldItem(itemRev);
							wireMaterials[i] = getWireMaterial(itemRev,bomcount);
							assemblyItems[i] = getAssemblyItem(itemRev);
							waveSolderingItems[i] = getWaveSolderingItem(itemRev);
							insulationMaterials[i] = getInsulationMaterial(itemRev,bomcount);
							auxMaterials[i] = getAuxMaterial(itemRev);
						}
					}
				}
			}
			catch (TCException e1)
			{
				e1.printStackTrace();
				logger.error(e1);
			}
		}
		else if (src.equals(btnCancel))
		{
			dialogResultId = ID_CANCEL;
		}
		this.dispose();
	}
	
	private String getAuxMaterial(TCComponentItemRevision itemRev)
	{
		try
		{
			String name = itemRev.getProperty("object_name");
			TCComponentForm form = (TCComponentForm) itemRev.getRelatedComponent("IMAN_master_form_rev");
			return name + " " + form.getProperty("p5_compcode") + " " + form.getProperty("p5_standard");
		}
		catch (TCException e)
		{
			e.printStackTrace();
			logger.error(e);
		}
		return null;
	}

	private WeldItem getWeldItem(TCComponentItemRevision itemRev)
	{
		try
		{
			TCComponentForm form = (TCComponentForm) itemRev.getRelatedComponent("IMAN_master_form_rev");
			String compCode = form.getProperty("p5_compcode");
			String material = form.getProperty("p5_material") + " " 
			+ form.getProperty("p5_matmark") + " " 
			+ form.getProperty("p5_matspec");
			String itemName = itemRev.getProperty("object_name");
			return new WeldItem(0, compCode, itemName, material, "");
		}
		catch (TCException e)
		{
			e.printStackTrace();
			logger.error(e);
		}
		return null;
	}
	
	private InsulationMaterial getInsulationMaterial(TCComponentItemRevision itemRev,String bomcount)
	{
		try
		{
			TCComponentForm form = (TCComponentForm) itemRev.getRelatedComponent("IMAN_master_form_rev");
			String compCode = form.getProperty("p5_compcode");
			String materialName = form.getProperty("p5_material");
			String materialNO = form.getProperty("p5_matmark");
			String techCondition = form.getProperty("p5_matcond");
			String num = bomcount;//getBOMLineNum(itemRev);
			return new InsulationMaterial(0, compCode, materialName, materialNO, techCondition, "", "", num, "");
		}
		catch (TCException e)
		{
			e.printStackTrace();
			logger.error(e);
		}
		return null;
	}

	private WireMaterial getWireMaterial(TCComponentItemRevision itemRev,String bomcount)
	{
		try
		{
			TCComponentForm form = (TCComponentForm) itemRev.getRelatedComponent("IMAN_master_form_rev");
			String compCode = form.getProperty("p5_compcode");
			String materialName = form.getProperty("p5_material");
			String materialNO = form.getProperty("p5_matmark") + " " + form.getProperty("p5_matcond");
			String num = bomcount;//;getBOMLineNum(itemRev);
			return new WireMaterial(0, compCode, materialName, materialNO, "", "", "", "", "", num, "");
		}
		catch (TCException e)
		{
			e.printStackTrace();
			logger.error(e);
		}
		return null;
	}
	
	private String getBOMLineNum(TCComponentItemRevision itemRev)
	{
		String num = "1";
		try
		{
			String id = itemRev.getProperty("item_id");
			TCComponentItemRevision topRev = getTopItemRev(itemRev);
			TCSession tcSession = (TCSession) AIFUtility.getDefaultSession();
			TCComponentBOMWindowType bomWindowType = (TCComponentBOMWindowType) tcSession.getTypeComponent("BOMWindow");
			TCComponentBOMWindow bomWindow = bomWindowType.create(null);
			TCComponentBOMLine topbomline = bomWindow.setWindowTopLine(null, topRev, null, null);
			if (topbomline != null)
			{
				int count = getBOMLineCount(id, topbomline, 1);
				num = String.valueOf(count);
			}
		}
		catch (TCException e)
		{
			e.printStackTrace();
			logger.error(e);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			logger.error(e);
		}
		return num;
	}
	
	private TCComponentItemRevision getTopItemRev(TCComponentItemRevision itemRev)
	{
		TCComponentItemRevision itemRevision = null;
		try
		{
			TCComponent[] comps = itemRev.whereUsed(TCComponentItemRevision.WHERE_USED_ALL);
			if (comps.length > 0)
			{
				itemRev = (TCComponentItemRevision) comps[comps.length - 1];
				itemRevision = getTopItemRev(itemRev);
			}
			else
			{
				itemRevision = itemRev;
			}
		}
		catch (TCException e)
		{
			e.printStackTrace();
			logger.error(e);
		}
		return itemRevision;
	}
	
	private int getBOMLineCount(String id, TCComponentBOMLine topbomline, int num)
	{
		int count = 0;
		try
		{
			AIFComponentContext[] children = topbomline.getChildren();
			for (int i = 0; i < children.length; i++)
			{
				TCComponentBOMLine bomline = (TCComponentBOMLine) children[i].getComponent();
				String bomID = bomline.getProperty("bl_item_item_id");
				String bomcount = bomline.getProperty("bl_quantity");
				bomcount = bomcount.isEmpty() ? "1" : bomcount;
				int icount = Integer.valueOf(bomcount);
				icount = num * icount;
				if (bomID.equals(id))
				{
					count += icount;
					continue;
				}
				count += getBOMLineCount(id, bomline, icount);
			}
		}
		catch (TCException e)
		{
			e.printStackTrace();
			logger.error(e);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			logger.error(e);
		}
		return count;
	}

	private AssemblyItem getAssemblyItem(TCComponentItemRevision itemRev)
	{
		try
		{
			TCComponentForm form = (TCComponentForm) itemRev.getRelatedComponent("IMAN_master_form_rev");
			String compCode = "";
			if(itemRev.getType().endsWith("standardRevision"))
			{
				if(form.getProperty("p5_compcode").equals("") || form.getProperty("p5_compcode")==null)
				{
					 compCode = itemRev.getProperty("item_id");
				}else{
					 compCode = form.getProperty("p5_compcode");
				}
			}
			else
			{
			 compCode = form.getProperty("p5_compcode");
			}
			String itemName = itemRev.getProperty("object_name");
			return new AssemblyItem(0, itemName, compCode, "", "");
		}
		catch (TCException e)
		{
			e.printStackTrace();
			logger.error(e);
		}
		return null;
	}

	private WaveSolderingItem getWaveSolderingItem(TCComponentItemRevision itemRev)
	{
		try
		{
			TCComponentForm form = (TCComponentForm) itemRev.getRelatedComponent("IMAN_master_form_rev");
			String compCode = form.getProperty("p5_compcode");
			String itemName = itemRev.getProperty("object_name");
			return new WaveSolderingItem(0, compCode, itemName, "");
		}
		catch (TCException e)
		{
			e.printStackTrace();
			logger.error(e);
		}
		return null;
	}
	
	public WeldItem[] getWeldItems()
	{
		return weldItems;
	}
	
	public InsulationMaterial[] getInsulationMaterials()
	{
		return insulationMaterials;
	}

	public WireMaterial[] getWireMaterials()
	{
		return wireMaterials;
	}

	public AssemblyItem[] getAssemblyItems()
	{
		return assemblyItems;
	}

	public WaveSolderingItem[] getWaveSolderingItems()
	{
		return waveSolderingItems;
	}
	public String[] getAuxMaterials()
	{
		return auxMaterials;
	}
	public List<TCComponentItemRevision>  getlistItemR() {
		return listItemR;
	}
	public void setList(List<TCComponentItemRevision> list) {
		this.list = list;
	}

	@Override
	public void valueChanged(TreeSelectionEvent e)
	{
		bomlines = bomTreeTable.getSelectedBOMLines();
		boolean isOK = true;
		try
		{
			for (int i = 0; i < bomlines.length; i++)
			{
				String bomType = bomlines[i].getItemRevision().getType();
				boolean b = false;
				for (int j = 0; j < nodeTypes.length; j++)
				{
					if (bomType.equals(nodeTypes[j]))
					{
						b = true;
						break;
					}
				}
				isOK = isOK ? b : false;
			}
		}
		catch (TCException e1)
		{
			e1.printStackTrace();
			logger.error(e1);
		}
		btnOK.setEnabled(isOK);
	}
}
